package com.example.myapplicationndk.ativity;

import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public abstract class CurrentAdapter<T> extends RecyclerView.Adapter<CurrentAdapter.ViewHolder> {
    private List<T> localDataSet;
    /*布局文件id*/
    private int layoutId;

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private View itemView;
        /*控件个数未知*/
        private SparseArray<View> views;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
            views = new SparseArray<View>();
        }

        /*通过view的id添加到views中，get()查找，如果存在返回该view，不存在则添加并返回*/
        public <T extends View> T getView(int viewId) {
            View view = views.get(viewId);
            if (view == null) {
                view = itemView.findViewById(viewId);
                views.put(viewId, view);
            }
            return (T) view;
        }

        ;
    /*  
    这个方法让我觉得有点麻烦，难道以后新加的控件都需要写一个相似的方法？
    public ViewHolder setText(int viewId,String text)
        {
            TextView textView=getView(viewId);
            textView.setText(text);
            return this;
        }
      */

    }

    /*有参构造传入参数*/
    public CurrentAdapter(List<T> localDataSet, int layoutId) {
        this.localDataSet = localDataSet;
        this.layoutId = layoutId;
    }


    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(layoutId, viewGroup, false);

        return new ViewHolder(view);
    }


    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        convert(viewHolder, localDataSet.get(position));
    }

    /*定义外部接口，实现对view添加和设置*/
    public abstract void convert(ViewHolder holder, T t);

    @Override
    public int getItemCount() {
        return localDataSet.size();
    }

    @Override
    public void onViewRecycled(@NonNull ViewHolder holder) {
        super.onViewRecycled(holder);
    }
}

